package com.atguigu.jxc.service.impl;
import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.dao.GoodsDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {

    @Autowired
    private DamageListGoodsDao damageListGoodsDao;

    @Autowired
    private DamageListDao damageListDao;

    @Autowired
    private GoodsDao goodsDao;

    //保存报损单详情的同时还要向报损单表中保存数据所以要用到事务
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServiceVO save(DamageList damageList,  String damageListGoodsStr, String damageNumber) {
        DamageList damageListVo = new DamageList();
        damageListVo.setUserId(1);//不知道怎么获取直接给了，不过只有userId=1的那个才是管理员 TODO
        damageListVo.setDamageNumber(damageNumber);
        damageListVo.setDamageDate(damageList.getDamageDate());
        damageListVo.setRemarks(damageList.getRemarks());
        damageListVo.setTrueName(damageList.getTrueName());
        damageListDao.save(damageListVo);//设置id自增


        Gson gson = new Gson();
        //类型要转换成list
        DamageListGoods[] damageListGoodsVo = gson.fromJson(damageListGoodsStr, DamageListGoods[].class);
        for (DamageListGoods listGoodsStr : damageListGoodsVo) {
            DamageListGoods damageListGoods = new DamageListGoods();
            damageListGoods.setDamageListId(damageListVo.getDamageListId());
            damageListGoods.setGoodsId(listGoodsStr.getGoodsId());
            damageListGoods.setGoodsCode(listGoodsStr.getGoodsCode());
            damageListGoods.setGoodsName(listGoodsStr.getGoodsName());
            damageListGoods.setGoodsModel(listGoodsStr.getGoodsModel());
            damageListGoods.setGoodsUnit(listGoodsStr.getGoodsUnit());
            damageListGoods.setGoodsNum(listGoodsStr.getGoodsNum());
            damageListGoods.setPrice(listGoodsStr.getPrice());
            damageListGoods.setTotal(listGoodsStr.getTotal());
            Goods goodsById = goodsDao.getGoodsById(listGoodsStr.getGoodsId());
            damageListGoods.setGoodsTypeId(goodsById.getGoodsTypeId());
            damageListGoodsDao.save(damageListGoods);
        }

        return new ServiceVO(SuccessCode.SUCCESS_CODE,SuccessCode.SUCCESS_MESS);
    }

    @Override
    public List<DamageListGoods> getDamageGoodsList(Integer damageListId) {
        return damageListGoodsDao.getDamageGoodsList(damageListId);
    }

}
